var goods_id = getQueryString("goods_id");
var time_goods_id = getQueryString("time_goods_id");
var inviter_id = getQueryString("inviter_id");
var pintuangroup_share_id = getQueryString("pintuangroup_share_id");
var map_list = [];
var map_index_id = "";
var goods_max_limit = 0;
var goods_subscribe = null;
var goods_multi_limit = 1;
$(function () {
    if(checkLoginStatus('only_check')) {
        // baseApi.get("/member/inviter_check", {
        //     inviter_id: inviter_id
        // }, function (e) {
        //     console.log(e);
        // })
    }
        var ua = navigator.userAgent.toLowerCase();
        if(true || ua.match(/MicroMessenger/i)=="micromessenger") {
            //记录浏览历史
            $.get(ApiUrl + "/Goods/addbrowse/gid/" + getQueryString("goods_id"));
            var e = getCookie("key");
            var t = function (e, t) {
                e = parseFloat(e) || 0;
                if (e < 1) {
                    return ""
                }
                var o = new Date;
                o.setTime(e * 1e3);
                var a = "" + o.getFullYear() + "-" + (1 + o.getMonth()) + "-" + o.getDate();
                if (t) {
                    a += " " + o.getHours() + ":" + o.getMinutes() + ":" + o.getSeconds()
                }
                return a
            };
            var o = function (e, t) {
                e = parseInt(e) || 0;
                t = parseInt(t) || 0;
                var o = 0;
                if (e > 0) {
                    o = e
                }
                if (t > 0 && o > 0 && t < o) {
                    o = t
                }
                return o
            };
            template.helper("isEmpty",
                function (t) {
                    return $.isEmpty(t);
                });

            function a() {
                var e = $("#mySwipe")[0];
                window.mySwipe = Swipe(e, {
                    continuous: false,
                    stopPropagation: true,
                    callback: function (e, t) {
                        $(".goods-detail-turn").find(".now_page").text(e + 1);
                    }
                });
            }

            r(goods_id);

            function i(e, t) {
                $(e).addClass("current").siblings().removeClass("current");
                var o = $(".spec").find("a.current");
                var a = [];
                $.each(o,
                    function (e, t) {
                        a.push(parseInt($(t).attr("specs_value_id")) || 0)
                    });
                var i = a.sort(function (e, t) {
                    return e - t;
                }).join("|");
                goods_id = t.spec_list[i];
                r(goods_id);
            }

            function s(e, t) {
                var o = e.length;
                while (o--) {
                    if (e[o] === t) {
                        return true;
                    }
                }
                return false;
            }

            $.sValid.init({
                rules: {
                    buynum: "digits"
                },
                messages: {
                    buynum: "请输入正确的数字"
                },
                callback: function (e, t, o) {
                    if (e.length > 0) {
                        var a = "";
                        $.map(t, function (e, t) {
                            a += "<p>" + e + "</p>"
                        });
                        layer.open({content: a, skin: 'msg', time: 2});
                    }
                }
            });

            function n() {
                $.sValid();
            }

            function r(goods_id) {
                baseApi.get("/goods/goods_detail", {
                        goods_id: goods_id,
                        // time_goods_id:getQueryString('time_goods_id'),
                        inviter_id: inviter_id
                    }, function (e) {
                        var l = e.goods_detail;
	                    if(!l || !l.goods_info) {
	                        var html = '<div class="sctouch-norecord cart">\n' +
		                        '               <div class=""> </div>\n' +
		                        '                <dl>\n' +
		                        '                    <dt>商品不存在或已下架</dt>\n' +
		                        '                    <dd>去挑一些中意的商品吧</dd>\n' +
		                        '                </dl>\n' +
		                        '                <a class="btn open-url" style="background-color: red; width: 4rem;height: 1.5rem;line-height: 1.5rem; border-color: red;" data-url="../mall/shop_portal.html" data-inviter_id="'+inviter_id+'"><span style="color: #FFFFFF;">随便逛逛</span></a>\n' +
		                        '            </div>';

		                    $('#goods-body').html(html).removeClass('mui-hidden');
		                    $('.show-detail').hide();
		                    $('#share_product_detail_foot_html').hide();
	                        return;
                        }
						window.goods_info = l;
                        goods_id = l.goods_info.goods_id;
                        // time_goods_id = l.goods_info.time_goods.time_goods_id;
                        // goods_subscribe = l.goods_info.goods_subscribe;
                        goods_max_limit = l.goods_info.goods_max_limit;
                        goods_multi_limit = l.goods_info.goods_min_limit;

                        if (l.goods_image) {
                            var d = l.goods_image.split(",");
                            l.goods_image = d
                        } else {
                            l.goods_image = []
                        }
                        if (l.goods_info.spec_name) {
                            var c = $.map(l.goods_info.spec_name,
                                function (e, t) {
                                    var o = {};
                                    o["goods_spec_id"] = t;
                                    o["goods_spec_name"] = e;
                                    if (l.goods_info.spec_value) {
                                        $.map(l.goods_info.spec_value,
                                            function (e, a) {
                                                if (t == a) {
                                                    o["goods_spec_value"] = $.map(e,
                                                        function (e, t) {
                                                            var o = {};
                                                            o["specs_value_id"] = t;
                                                            o["specs_value_name"] = e;
                                                            return o
                                                        })
                                                }
                                            });
                                        return o
                                    } else {
                                        l.goods_info.spec_value = []
                                    }
                                });
                            l.goods_map_spec = c
                        } else {
                            l.goods_map_spec = []
                        }
                        if (l.goods_info.is_virtual == "1") {
                            l.goods_info.virtual_indate_str = t(l.goods_info.virtual_indate, true);
                            l.goods_info.buyLimitation = o(l.goods_info.virtual_limit, l.goods_info.upper_limit)
                        }
                        if (l.goods_info.is_presell == "1") {
                            l.goods_info.presell_deliverdate_str = t(l.goods_info.presell_deliverdate)
                        }
                        if (l.goods_info.mobile_body){
                            console.log(typeof(l.goods_info.mobile_body))

                            $('#goods-body').append(l.goods_info.mobile_body)
                        }
                        var _ = template("product_detail", l);
                        $("#product_detail_html").html(_);
                        var _ = template("product_detail_sepc", l);
                        $("#product_detail_spec_html").html(_);
                        var _ = template("product_detail_foot", l);
                        $("#share_product_detail_foot_html").html(_);
                        var _ = template("voucher_script", l);
                        $("#voucher_html").html(_);
                        if (getCookie("cart_count")) {
                            if (getCookie("cart_count") > 0) {
                                $("#cart_count").html("<sup>" + getCookie("cart_count") + "</sup>")
                            }
                        }
                        a();
                         //time_differ();
                        //给轮播图高度
                        $('.goods-detail-top').css('height', $(window).width());
                        //详情图懒加载
                        $(window).scroll(function () {
                            if ($("img.lazyload").length == 0) {
                                return;
                            }
                            if ($('').length > 0 && $('.goods-body').height() >= 600) {
                                $('').show().removeClass('wait');
                            }
                            if (($(window).scrollTop() + $(window).height()) > $("img.lazyload").eq(0).offset().top) {
                                $("img.lazyload").eq(0).attr('src', $("img.lazyload").eq(0).attr('data-original')).removeClass('lazyload').removeAttr('data-original');
                            }
                        })
                        $('').on('tap',function () {
                            $('.goods-body').css('max-height', 'initial');
                            $('').remove();
                        });

                        $(".pddcp-arrow").on('tap',function () {
                            $(this).parents(".pddcp-one-wp").toggleClass("current")
                        });
                        var p = {};
                        p["spec_list"] = l.spec_list;
                        $(".spec a").on('tap',function () {
                            var e = this;
                            i(e, p)
                        });
                        $(".minus").on('tap',function () {
                            var e = $(".buy-num").val();
                            if (e > 1) {
                                $(".buy-num").val(parseInt(e - goods_multi_limit))
                            }
	                        check_storage();
                        });
                        $(".add").on('tap',function () {
                            var e = parseInt($(".buy-num").val());
                            if (e < l.goods_info.goods_storage) {
                                $(".buy-num").val(parseInt(e + goods_multi_limit))
                            }

                            check_storage();
                        });
                        if (l.goods_info.is_goodsfcode == "1") {
                            $(".minus").hide();
                            $(".add").hide();
                            $(".buy-num").attr("readOnly", true)
                        }
                        $(".add-cart").on('tap',function () {
                            if (!$('#product_detail_spec_html').hasClass('up')) {
	                            check_storage();
                                return;
                            }
                            $.ajax({
                                url: ApiUrl + "/Membercart/cart_add.html",
                                data: {
                                    key: e,
                                    goods_id: goods_id,
                                    time_goods_id: time_goods_id,
                                    quantity: t
                                },
                                type: "post",
                                success: function (e) {
                                    var t = $.parseJSON(e);
                                    console.log(t);
                                    if (t.code == 10000) {
                                        show_tip();
                                        if (getCookie("key")) {
                                            delCookie("cart_count");
                                            getCartCount();

                                        } else {
                                            var a = 0;
                                            if (getCookie("cart_count") != null) {
                                                a = parseInt(getCookie("cart_count"));
                                            }
                                            a = a + 1;
                                            delCookie("cart_count");
                                            addCookie("cart_count", a);
                                        }
                                        $("#cart_count").html("<sup>" + getCookie("cart_count") + "</sup>")
                                    } else {
                                        layer.open({
                                            content: t.message,
                                            btn: '确定',
                                            yes: function (index) {
                                                layer.close(index);
                                                // 去登录
                                                if(t.login === '0') {
                                                    delCookie('key');
                                                    pageChange('../member/login_mobile.html');
                                                }
                                            }
                                        });
                                    }

                                }
                            })

                        });
                        if (l.goods_info.is_virtual == "1") {
                            $(".buy-now").on('tap',function () {
                                if (!$('#product_detail_spec_html').hasClass('up')) {
	                                check_storage();
                                    return;
                                }
                                // var e = getCookie("key");
                                // if (!e) {
                                //     pageChange("../member/login_mobile.html");
                                //     return false
                                // }
                                var t = parseInt($(".buy-num").val()) || 0;
                                if (t < 1) {
                                    layer.open({content: '参数错误！', skin: 'msg', time: 2});
                                    return
                                }
                                if (t > l.goods_info.goods_storage) {
                                    layer.open({content: '库存不足！', skin: 'msg', time: 2});
                                    return
                                }
                                if (l.goods_info.buyLimitation > 0 && t > l.goods_info.buyLimitation) {
                                    layer.open({content: '超过限购数量！', skin: 'msg', time: 2});
                                    return
                                }
                                var o = {};
                                o.key = e;
                                o.cart_id = r;
                                o.quantity = t;
                                $.ajax({
                                    type: "post",
                                    url: ApiUrl + "/Membervrbuy/buy_step1.html",
                                    data: o,
                                    dataType: "json",
                                    success: function (e) {
                                        if (e.code != 10000) {
                                            layer.open({content: e.message, skin: 'msg', time: 2});
                                        } else {
                                            pageChange("../order/vr_buy_step1.html?goods_subscribe_id="+goods_subscribe.id+"&goods_id=" + r + "&quantity=" + t+"&inviter_id=" + inviter_id)
                                        }
                                    }
                                })
                            })
                        } else {
                            $(".buy-now").unbind().on('tap',function () {

	                            if (!$('#product_detail_spec_html').hasClass('up')) {
		                            check_storage();
		                            return;
	                            }
                                var t = parseInt($(".buy-num").val()) || 0;
                                if (t < 1) {
                                    layer.open({content: '参数错误！', skin: 'msg', time: 2});
                                    return
                                }

                                if (goods_max_limit > 0) {
                                    if (t > goods_max_limit) {
                                        layer.open({
                                            content: '超过限购数量！最多购买：' + goods_max_limit,
                                            skin: 'msg',
                                            time: 2
                                        });
                                        return
                                    }
                                }

                                if (t > l.goods_info.goods_storage) {
                                    layer.open({content: '库存不足！', skin: 'msg', time: 2});
                                    return
                                }
                                var o = {};

	                            try {
		                            var o = {};
		                            o.key = getCookie("key");
		                            o.cart_id = l.goods_info.goods_id + "|" + t;
		                            baseApi.post("/Memberbuy/buy_step1.html", o,function (e) {
			                            pageChange("../order/buy_step1.html", {
				                            // goods_subscribe_id: goods_subscribe.id,
				                            goods_id: goods_id,
				                            buynum: t,
				                            // time_goods_id: l.goods_info.time_goods ? l.goods_info.time_goods.time_goods_id : 0
			                            });
		                            });
                                } catch (e) {
		                            layer.open({content: e, skin: 'msg', time: 2});
	                            }
                            })
                        }

                        //立刻拼团,开团
                        if (l.goods_info.is_virtual == "1") {
                            $(".pintuan-now").on('tap',function () {
                                layer.open({
                                    content: '虚拟产品不能参加拼团'
                                    , skin: 'msg'
                                    , time: 2 //2秒后自动关闭
                                });
                            });
                        } else {
                            $("#pintuan-now").on('tap',function () {
                                $('#product_detail_spec_html').removeClass('down').addClass('up')
                                $("#product_detail_foot_html .pintuan-now").attr('fieldid', $(this).attr('fieldid'))
                                $("#product_detail_foot_html .pintuan-now").text(sc_lang.join_the_group)
                                $("#product_detail_foot_html").css('z-index', '30')
                            });
                            $(".pintuan-now").on('tap',function () {
                                if (!$('#product_detail_spec_html').hasClass('up')) {
                                    return;
                                }
                                // var e = getCookie("key");
                                // if (!e) {
                                //     pageChange("../member/login_mobile.html")
                                // } else {
                                var t = parseInt($(".buy-num").val()) || 0;
                                if (t < 1) {
                                    layer.open({content: '参数错误！', skin: 'msg', time: 2});
                                    return
                                }
                                if (t > l.goods_info.goods_storage) {
                                    layer.open({content: '库存不足！', skin: 'msg', time: 2});
                                    return
                                }
                                //获取拼团ID 用于拼团下单
                                var pintuan_id = l.goods_info.pintuan_id
                                if (pintuan_id < 1) {
                                    layer.open({content: '拼团ID参数错误！', skin: 'msg', time: 2});
                                    return
                                }
                                //获取当前购买的发起拼团ID,用于参团。
                                var pintuangroup_id = parseInt($(this).attr('fieldid'));
                                //判断当前购买数量是否小于购买拼团的数量限制
                                var pintuan_limit_quantity = l.goods_info.pintuan_limit_quantity
                                if (t > pintuan_limit_quantity) {
                                    layer.open({
                                        content: '拼团最多只能购买' + pintuan_limit_quantity + '件商品',
                                        skin: 'msg',
                                        time: 2
                                    });
                                    return
                                }

                                var o = {};
                                o.key = e;
                                o.cart_id = r + "|" + t;


                                $.ajax({
                                    type: "post",
                                    url: ApiUrl + "/Memberbuy/buy_step1.html?pintuangroup_id=0",
                                    data: o,
                                    dataType: "json",
                                    success: function (e) {
                                        if (e.code != 10000) {
                                            layer.open({content: e.message, skin: 'msg', time: 2});
                                        } else {
                                            pageChange("../order/buy_step1.html?goods_id=" + r + "&buynum=" + t + "&pintuan_id=" + pintuan_id + "&pintuangroup_id=" + pintuangroup_id)
                                        }
                                    }
                                })
                                // }
                            })
                        }

                        $("#buynum").blur(n);
                        $.animationUp({
                            valve: ".animation-up,#goods_spec_selected",
                            wrapper: "#product_detail_spec_html",
                            scroll: "#product_roll",
                            start: function () {
                                $("#share_product_detail_foot_html").css('z-index', '30')
                            },
                            close: function () {
                                $("#share_product_detail_foot_html").css('z-index', '1')
                                $("#share_product_detail_foot_html .pintuan-now").attr('fieldid', '0')
                                $("#share_product_detail_foot_html .pintuan-now").text(sc_lang.immediately_open_regiment)
                            }
                        });
                        $.animationUp({
                            valve: "#getVoucher",
                            wrapper: "#voucher_html",
                            scroll: "#voucher_roll"
                        });
                        $("#voucher_html").on("tap", ".btn",
                            function () {
                                getFreeVoucher($(this).attr("data-tid"))
                            });
                    }
                )
            }

            $("#product_detail_html").on("tap", "#get_area_selected",
                function () {
                    $.areaSelected({
                        success: function (e) {
                            $("#get_area_selected_name").html(e.area_info);
                            var t = e.area_id_2 == 0 ? e.area_id_1 : e.area_id_2;
                            $.getJSON(ApiUrl + "/Goods/calc.html", {
                                    goods_id: goods_id,
                                    area_id: t
                                },
                                function (e) {
                                    $("#get_area_selected_whether").html(e.result.if_deliver_cn);
                                    $("#get_area_selected_content").html(e.result.content).show();
                                    if (!e.result.if_deliver) {
                                        $(".buy-handle").addClass("no-buy")
                                    } else {
                                        $(".buy-handle").removeClass("no-buy")
                                    }
                                })
                        }
                    })
                });
            $("body").on("tap", "#goodsBody,#goodsBody1",
                function () {
                    pageChange("../mall/product_info.html?goods_id=" + goods_id)
                });
            $("body").on("tap", "#goodsEvaluation,#goodsEvaluation1",
                function () {
                    pageChange("../mall/product_eval_list.html?goods_id=" + goods_id)
                });

        } else {
            mui.toast('请使用微信浏览器打开');
            return false;
        }


});

function show_tip() {
    var e = $(".goods-pic > img").clone().css({
        "z-index": "999",
        height: "3rem",
        width: "3rem"
    });
    e.fly({
        start: {
            left: $(".goods-pic > img").offset().left,
            top: $(".goods-pic > img").offset().top - $(window).scrollTop()
        },
        end: {
            left: $("#cart_count").offset().left + 40,
            top: $("#cart_count").offset().top - $(window).scrollTop(),
            width: 0,
            height: 0
        },
        onEnd: function () {
            e.remove()
        }
    })
}
//获取时间差
function time_differ(){
    baseApi.get("goods/remain_time",
        {
            time_goods_id:time_goods_id
        },
        function(data){
            console.log(data);
            dtime = data.remain_time;
            show_time(dtime);
        });
}

/**
 * 库存检查 & 计算税费，运费
 */
function check_storage() {
	// var goods_num = $('#buynum').val().toInt();
	if(window.goods_info) {
		var e = window.goods_info;
		$("#get_area_selected_whether").html(e.goods_hair_info.if_store_cn);
		$("#get_area_selected_content").html(e.goods_hair_info.content).show();
		
		if(e.goods_info.tax) $('#product_detail_spec_html').find('.goods-tax').show().find('span').text(e.goods_info.tax);
		$('#product_detail_spec_html').find('.goods-freight').show().find('span').text(e.goods_info.goods_freight > 0 ? e.goods_info.goods_freight.number_format(2) : '包邮');
		if (!e.goods_hair_info.if_store) {
			$(".buy-handle").addClass("no-buy")
		} else {
			$(".buy-handle").removeClass("no-buy")
		}
	}
	// $.getJSON(ApiUrl + "/Goods/calc.html", {
	// 		time_goods_id: time_goods_id,
	// 		goods_id: goods_id,
	// 		area_id: window.area_id,
	// 		goods_num: goods_num,
	// 	    goods_subscribe_id: goods_subscribe.id
	// 	},
	// 	function (e) {
	// 		$("#get_area_selected_whether").html(e.result.if_store_cn);
	// 		$("#get_area_selected_content").html(e.result.content).show();

	// 		if(e.result.tax_fee) $('#product_detail_spec_html').find('.goods-tax').show().find('span').text(e.result.tax_fee);
	// 		$('#product_detail_spec_html').find('.goods-freight').show().find('span').text(e.result.freight > 0 ? e.result.freight.number_format(2) : '包邮');
	// 		if (!e.result.if_store) {
	// 			$(".buy-handle").addClass("no-buy")
	// 		} else {
	// 			$(".buy-handle").removeClass("no-buy")
	// 		}
	// 	})
}
function show_time(timediff){
    timediff = timediff < 0 ? 0 : timediff;
    //获取时间差

    //获取还剩多少小时
    var hour = add0(parseInt(timediff/(60*60)));
    //获取还剩多少分钟
    var minute = add0(parseInt((timediff - hour*60*60)/60));
    //获取还剩多少秒
    var second = add0(timediff - hour*60*60 - minute*60);
    //输出还剩多少时间
    document.getElementById('hour').innerHTML = hour;
    document.getElementById('minute').innerHTML = minute;
    document.getElementById('second').innerHTML = second;

    // 设置定时器
    if(timediff) {
        setTimeout(function () {
            show_time(timediff - 1);
        },1000);
    }
}

$('body').on('tap', '.show-detail', function () {
    $(this).toggle();
    $('#goods-body').removeClass('mui-hidden');
});